﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JyFramework
{
    public class EventController : BaseController, IEvent
    {
        public string Name { get { return _name; } }

        public HandlerMsg RegistMsgEvent;
        public HandlerMsg RemoveMsgEvent;

        public Dictionary<string, List<MessageHandler>> Events { get { return _events; } }

        public EventController(string name = "EventController")
        {
            _name = name;
            _events = new Dictionary<string, List<MessageHandler>>();
        }

        /// <summary>
        /// 添加控制器时初始化函数
        /// </summary>
        public virtual void OnInit()
        {
        }

        /// <summary>
        /// 移除控制器时执行的函数
        /// </summary>
        public virtual void OnRemove()
        {
            _events.Clear();
        }

        /// <summary>
        /// 注册事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="eventAction"></param>
        public void RegistEvent(string name, MessageHandler eventAction)
        {
            List<MessageHandler> actions = null;
            if (_events.TryGetValue(name, out actions))
            {
                actions.Add(eventAction);
            }
            else
            {
                actions = new List<MessageHandler>();
                actions.Add(eventAction);
                _events.Add(name, actions);
            }
            if (RegistMsgEvent != null) RegistMsgEvent(name, eventAction);
        }

        /// <summary>
        /// 通知事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="args"></param>
        public void NotifyEvent(string name, params object[] args)
        {
            List<MessageHandler> actions = null;
            if (_events.TryGetValue(name, out actions))
            {
                foreach (var e in actions)
                {
                    e(args);
                }
            }
            else
            {
                // log the event name = name is null
            }
        }

        /// <summary>
        /// 移除事件
        /// </summary>
        /// <param name="name"></param>
        /// <param name="eventAction"></param>
        public void RemoveEvent(string name, MessageHandler eventAction)
        {
            List<MessageHandler> actions = null;
            if (_events.TryGetValue(name, out actions))
            {
                actions.Remove(eventAction);
                if (actions.Count <= 0)
                {
                    _events[name].Clear();
                    _events.Remove(name);
                }
            }

            if (RemoveMsgEvent != null) RemoveMsgEvent(name, eventAction);
        }

        protected string _name;
        protected Dictionary<string, List<MessageHandler>> _events;
    }
}
